<template>
    <div>
        <el-card class="head-card">
            <i class="el-icon-s-fold"></i><span style="font-size: 18px">大健康综合管理后台</span>
            <el-breadcrumb separator-class="el-icon-arrow-right">
                <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
                <el-breadcrumb-item :to="{ path: '/' }">商品系统</el-breadcrumb-item>
                <el-breadcrumb-item ><strong>品类管理</strong></el-breadcrumb-item>
            </el-breadcrumb>
            <h1 style="color: #333744">品类管理</h1>
        </el-card>
        <el-card class="body-card">
            <h4 style="margin-top: 0">查询条件</h4>
            <el-form :inline="true" :model="condition" class="demo-form-inline">
                <el-form-item label="一级品类：">
                    <el-select v-model="condition.categoryName" clearable placeholder="请选择">
                        <el-option
                            v-for="item in categoryNameList"
                            :label=item
                            :value=item>
                        </el-option>
                    </el-select>
                </el-form-item>
                &nbsp;
                <el-form-item label="创建日期：">
                    <el-date-picker v-model="condition.begin" type="datetime"
                                    value-format="yyyy-MM-dd HH:mm:ss"
                                    placeholder="选择开始时间" :picker-options="pickerOptions" style>
                    </el-date-picker>
                    &nbsp;
                    <el-form-item label="至">
                        <el-date-picker v-model="condition.end" type="datetime"
                                        value-format="yyyy-MM-dd HH:mm:ss"
                                        placeholder="选择结束时间" :picker-options="pickerOptions">
                        </el-date-picker>
                    </el-form-item>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="search">查询</el-button>
                    <el-button  type="success" @click="resetting">重置</el-button>
                </el-form-item>
            </el-form>
        </el-card>
        <el-card class="foot-card">
            <span>
                <el-button type="primary" icon="el-icon-plus"
                           style="padding-left: 30px; padding-right: 30px;  margin-right:30px "
                @click="addCategory">新增</el-button>
                <el-button type="primary" plain style="padding-left: 35px; padding-right: 35px;  margin-right:30px "
                           @click="updateStatus">下架
                </el-button>
            </span>
            <el-table
                :default-sort = "{prop: 'sequence', order: 'ascending'}"
                ref="multipleTable"
                :data="tableData"
                tooltip-effect="dark"
                style="width: 100%"
                @selection-change="handleSelectionChange">
                <el-table-column
                    type="selection"
                    width="55">
                </el-table-column>
                <el-table-column prop="id" label="品类ID" width="150"></el-table-column>
                <el-table-column prop="categoryName" label="品类名称" width="180"></el-table-column>
                <el-table-column prop="sequence" label="顺序" sortable width="100"></el-table-column>

                <el-table-column prop="status" label="状态">
                    <template slot-scope="scope">
                        <el-tag plain
                                :type="scope.row.status === 1 ? 'success' : 'danger'">
                            {{ scope.row.status === 1 ? '已上架' : '已下架' }}
                        </el-tag>
                    </template>
                </el-table-column>
                <el-table-column prop="createTime" label="创建时间" :formatter="dateFormatter"></el-table-column>
                <el-table-column label="操作" width="240">
                    <template slot-scope="scope">
                    <el-button type="warning" size="mini" @click="showEditDialog(scope.row)">编辑</el-button>
                    <el-button type="danger" size="mini" @click="removeById(scope.index, scope.row)">删除</el-button>
                    <el-button type="primary" size="mini" @click="viewById(scope.row)">查看</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <!-- 分页 -->
            <el-pagination style="margin-top: 10px"
                           background
                           @size-change="handleSizeChange"
                           @current-change="handleCurrentChange"
                           :current-page="condition.pageNum"
                           :page-sizes="[5, 10, 15]"
                           :page-size="condition.pageSize"
                           layout="total, sizes, prev, pager, next, jumper"
                           :total="pageBean.total">
            </el-pagination>
        </el-card>
        <!-- 添加品类弹窗 -->
        <el-dialog title="添加品类" :visible.sync="addDialogVisible" width="40%">
            <el-form :model="addEntity" label-width="80px">
                <el-form-item label="品类名称">
                    <el-input v-model="addEntity.categoryName"></el-input>
                </el-form-item>
                <el-form-item label="子品类" >
                    <el-input v-model="subTypes" style="width:53%"></el-input>
                    &nbsp;
                    <el-button icon="el-icon-plus" @click="addSubType">保存</el-button>
                    &nbsp;
                    <span>最少添加一个子类</span>
                </el-form-item>
                <el-form-item >
                    <el-tag v-for="tag in addEntity.subTypes" :key="tag" closable style="margin-right: 5px;"
                            @close="handleClose(tag)">
                        {{ tag }}
                    </el-tag>
                </el-form-item>
                <el-form-item label="品类描述">
                    <el-input v-model="addEntity.description" type="textarea" />
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="add">确认</el-button>
                    <el-button @click="addDialogVisible = false">取消</el-button>
                </el-form-item>
            </el-form>
        </el-dialog>
        <!-- 修改品类弹窗 -->
        <el-dialog title="修改品类" :visible.sync="editDialogVisible" width="40%">
            <el-form :model="editEntity" label-width="80px">
                <el-form-item label="品类名称">
                    <el-input v-model="editEntity.categoryName"></el-input>
                </el-form-item>
                <el-form-item label="子品类" >
                    <el-input v-model="subTypes" style="width:53%"></el-input>
                    &nbsp;
                    <el-button icon="el-icon-plus" @click="editSubType">保存</el-button>
                    &nbsp;
                    <span>最少添加一个子类</span>
                </el-form-item>
                <el-form-item >
                    <el-tag v-for="tag in editEntity.subTypes" :key="tag" closable style="margin-right: 5px;"
                            @close="handleCloseUpdate(tag)">
                        {{ tag }}
                    </el-tag>
                </el-form-item>
                <el-form-item label="品类描述">
                    <el-input v-model="editEntity.description" type="textarea" />
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="edit">确认</el-button>
                    <el-button @click="editDialogVisible = false">取消</el-button>
                </el-form-item>
            </el-form>
        </el-dialog>
    </div>
</template>

<script>
export default {
    name: "Category",
    data() {
        return {
            categoryNameList: [],
            pickerOptions: {},
            condition: {
                categoryName: "",
                begin: null,
                end: null,
                pageNum: 1,
                pageSize: 5
            },
            pageBean: {},
            pageNum: 1,
            pageSize: 5,
            total: 0,
            //表格数据
            tableData: [],
            //复选框
            multipleSelection: [],
            //添加
            addDialogVisible: false,
            addEntity: {
                subTypes: [],
                description:''
            },
            subTypes:'',
            //
            editDialogVisible: false,
            editEntity: {
                categoryName: '',
                subTypes: [],
                description: '',
            },
            //子品类
            categoryChildren:[],
            typeInfo:{}

        }
    },
    methods: {
        addCategory(){
            this.addDialogVisible =true;
        },
        // 删除子品类标签后，从集合中删除
        handleClose(tag) {
            this.addEntity.subTypes.splice(this.addEntity.subTypes.indexOf(tag), 1)
        },
        //添加品类
        add() {
            this.$axios.post('/category/add', this.addEntity)
                .then(res => {
                    this.addDialogVisible = false;
                    this.addEntity = {
                        subTypes: [],
                        description: ''
                    };
                    this.findByCondition();
                    this.findAllCategoryName();
                    this.$message.success("添加成功！");

                })
                .catch(err => {
                    this.$message.error(err);
                })
        },
        // 添加弹窗添加子品类
        addSubType() {
            this.addEntity.subTypes.push(this.subTypes);
            this.subTypes = '';
        },
        //修改品类
        edit() {
            this.$axios.put('/category/update', this.editEntity)
                .then(res => {
                    this.findByCondition();
                    this.findAllCategoryName();
                    this.$message.success("修改成功！");
                    this.editDialogVisible = false;
                })
                .catch(err => {
                    this.$message.error(err);
                })
        },
        // 编辑弹窗添加子品类
        editSubType() {
            this.editEntity.subTypes.push(this.subTypes);
            this.subTypes = '';
        },
        //删除子品类标签后，从集合中删除
        handleCloseUpdate(tag){
            this.editEntity.subTypes.splice(this.editEntity.subTypes.indexOf(tag), 1)
        },
        //编辑
        showEditDialog(row){
            this.editDialogVisible = true;
            this.typeInfo = row;
            console.log("typeInfo",this.typeInfo);
            this.editEntity = {
                categoryName: '',
                subTypes: [],
                description: '',
            },
                this.editEntity.id = row.id;
                this.editEntity.description = row.description;
                this.editEntity.categoryName = row.categoryName;
            for (let i = 0; i < this.categoryChildren.length; i++) {
                this.editEntity.subTypes.push(row.categoryChildren[i].categoryName);
            }

        },
        //查询子品类
        findChildrenCategory(){
            this.$axios.get(`/category/getAllChildrenCategory?id=${this.id}`).then(resp => {
                if (resp.data.code==200){
                    this.categoryChildren = resp.data.data;
                    console.log("categoryChildren",this.categoryChildren)
                }
            });
        },

        //分页条件查询
        findByCondition() {
            this.$axios.post('/category/findAllCategory', this.condition).then(resp => {
                console.log('resp', resp)
                this.pageBean = resp.data.data;
                this.tableData = resp.data.data.list;
                this.total = resp.data.data.total;
                console.log("tableData表格数据",this.tableData)
            });
        },
        search() {
            if (this.condition.categoryName == '' && this.condition.begin == '' && this.condition.end == '') {
                this.$message.warning("请输入搜索条件");
                return;
           }
            this.pageNum = 1;
            this.findByCondition();
        },

        //删除
        removeById(index,row){
            console.log("row",row)
            this.$confirm(`此操作将永久删除：${row.categoryName}, 是否继续?`, '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                //调用服务器端来删除
                this.$axios.get(`/category/deleteById?id=${row.id}`).then(resp => {
                    if (resp.data.code) {
                        this.$message.success(resp.data.message);
                    } else {
                        this.$message.error("删除失败");
                    }
                    //重新加载
                    this.findByCondition();
                });
            }).catch(() => {
                //什么也不写
            });
        },
        //查看
        viewById(row){
            this.$router.push({
                path: `/categoryDetails/${row.id}`,
                params: { id: row.id }
            });
        },
        //下架
        updateStatus() {
            //判断是否选中
            if (this.multipleSelection.length == 0) {
                this.$message.warning("请先选中要下架的品类");
                return;
            }
            //确认
            this.$confirm(`此操作将下架${this.multipleSelection.length}个品类,是否继续?`, '提示',
                {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                //1.把对象数组转成id的数组 (row表示数组中每个元素)
                let ids = this.multipleSelection.map(row => row.id);
                console.log("ids"+ids);
                //2.发送操作给服务器端
                this.$axios.post("/category/updateStatus", ids).then(resp => {
                    this.$message.success(`成功下架`);
                    //重新加载表格数据
                    this.findByCondition();
                    this.findAllCategoryName();
                });
            }).catch(() => {
                //不做什么
            });
        },

        //加载所有一级品类
        findAllCategoryName() {
            this.$axios.get('/category/findAllCategoryName').then(resp => {
                // 将服务器返回的数据解析并赋值给 options 数组
                this.categoryNameList = resp.data.data;
                console.log("一级品类名",this.categoryNameList)
            }).catch(error => {
                console.error(error);
            });
        },

        handleSelectionChange(val) {
            this.multipleSelection = val;
        },
        resetting() {
            // 重置所有输入框和选择器
            this.condition= {
                    categoryName: "",
                    begin: null,
                    end: null,
                    pageNum: 1,
                    pageSize: 5
            };
            this.findByCondition();
        },
        onSubmit() {
            console.log('submit!');
        },
        handleSizeChange(val) {
            console.log(`每页 ${val} 条`);
            this.condition.pageSize = val;
            this.findByCondition();
        },
        handleCurrentChange(val) {
            console.log(`当前页: ${val}`);
            this.condition.pageNum = val;
            this.findByCondition();
        },

        reloadData() {
            this.$axios.get("/category/findAll", {
                params: {
                    pageSize: this.pageSize,
                    pageNum: this.pageNum,
                    // name: this.name
                }
            }).then(res => {
                console.log("", res);
                this.total = res.data.data.total;
                this.tableData = res.data.data.records;
            })
        },
        dateFormatter(row, column, cellValue) {
            // 将时间戳转换为可读格式
            return new Date(cellValue).toLocaleString();
        },

    },
    created() {
        this.findByCondition();
        this.findAllCategoryName();
    },
}
</script>

<style scoped>
.head-card {
    text-align: left;
    padding-left: 18px;
    height: 160px;
}

.el-icon-s-fold {
    font-size: 23px;
    margin-right: 10px;
    margin-bottom: 40px;
}

.body-card {
    text-align: left;
    padding-left: 18px;
    width: 90%;
    display: block;
    margin: 30px auto;
    height: 130px;
    padding-bottom: 20px;
}

.foot-card {
    text-align: left;
    padding-left: 18px;
    width: 90%;
    display: block;
    margin: 0 auto;
}
.dialog .el-input{

}
</style>